package com.wanger.swa.config.dataSourceInstance;

import cn.hutool.core.io.IoUtil;
import com.wanger.swc.config.dataInstance.DataInstanceService;
import com.wanger.swc.config.dataInstance.model.DataInstanceType;
import com.wanger.swc.exception.BusEx;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @Author: wanger
 * @Date: 2025/3/11 9:48
 * @Description: Property内容类型验证与转换
 */
@Slf4j
@Component
public class PropertyDataInstance implements DataInstanceService {
    /**
     * 获取数据实例类型
     *
     * @return 类型
     */
    @Override
    public DataInstanceType getType() {
        return DataInstanceType.PROPERTY;
    }

    /**
     * 验证数据格式合法性
     *
     * @param content 要验证的数据内容
     */
    @Override
    public void verify(String content) {
        try {
            new Properties().load(IoUtil.toUtf8Stream(content));
        } catch (IOException e) {
            BusEx.throwEx("properties内容验证失败！");
        }
    }

    /**
     * 将数据转换为json数据
     *
     * @param content 原始数据
     * @return 转换后的数据
     */
    @Override
    public Object getJsonData(String content) {
        try {
            Properties proper = new Properties();
            proper.load(new InputStreamReader(IoUtil.toUtf8Stream(content), StandardCharsets.UTF_8));
            return proper;
        } catch (IOException e) {
            throw BusEx.create("properties内容读取失败！");
        }
    }
}
